﻿using Newtonsoft.Json;
using RemoteTool.Business.Tools.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RemoteTool.Business.Tools.Extension
{
    internal static class JsonExtension
    {
        public static T FromJsonFile<T>(this string filePath)
           where T : new()
        {
            var data = new T();
            if (!File.Exists(filePath))
            {
                LogHelper.WriteLog($"未找到配置文件->{filePath}");
                return data;
            }
            try
            {
                var tmp = File.ReadAllText(filePath);
                data = JsonConvert.DeserializeObject<T>(tmp);
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog("扎心了，抛异常了，Json反序列化失败了！", ex);
                return new T();
            }
            return data;
        }

        /// <summary>
        /// 保存可序列化对象到指定目录Json文件
        /// </summary>
        /// <param name="data">可序列化对象</param>
        /// <param name="filePath">xml文件全路径</param>
        /// <remarks>tlm,未完全测试</remarks>
        public static void ToJsonFile(this object data, string filePath)
        {
            try
            {
                if (string.IsNullOrEmpty(filePath)) return;
                FileInfo fileInfo = new FileInfo(filePath);
                if (!Directory.Exists(fileInfo.DirectoryName))
                {
                    Directory.CreateDirectory(fileInfo.DirectoryName);
                }
                File.WriteAllText(filePath, JsonConvert.SerializeObject(data));
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("转换为Json文件异常！", ex);
            }
        }
    }
}
